<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      ref="dataForm"
      :model="dataForm"
      :rules="dataRule"
      label-width="140px"
      @keyup.enter.native="dataFormSubmit()"
    >
      <el-form-item label="课题编码" prop="subjectCode">
        <el-input v-model="dataForm.subjectCode" />
      </el-form-item>
      <el-form-item label="课题名称" prop="researchName">
        <el-input v-model="dataForm.researchName" />
      </el-form-item>
      <el-form-item label="课题简称" prop="researchSimpleName">
        <el-input v-model="dataForm.researchSimpleName" />
      </el-form-item>
      <el-form-item label="课题PI" prop="piName">
        <el-input v-model="dataForm.piName" />
      </el-form-item>
      <el-form-item label="访视阶段" prop="vpInfo">
        <el-tag
          :key="tag"
          v-for="tag in dataForm.vpInfo"
          closable
          :disable-transitions="false"
          @close="handleClose(tag)">
          {{tag}}
        </el-tag>
        <el-input
          class="input-new-tag"
          v-if="inputVisible"
          v-model="inputValue"
          ref="saveTagInput"
          size="small"
          @keyup.enter.native="handleInputConfirm"
          @blur="handleInputConfirm"
        >
        </el-input>
        <el-button v-else class="button-new-tag" size="small" @click="showInput">+</el-button>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import research from '@/api/research'
import myUtils from '../../api/myUtils'
import { Container } from 'element-ui'
export default {
  data() {
    return {
      visible: true,
      dataRule: {
        subjectCode: [{ required: true, message: '课题编码不能为空', trigger: 'blur' }],
        researchName: [{ required: true, message: '课题名称不能为空', trigger: 'blur' }],
        vpInfo: [{ required: true, message: '访视阶段不能为空', trigger: 'blur' }]
      },
      dataForm: {
        vpInfo:["基线"],
        id: 0
      },
      inputVisible: false,
      inputValue: ''
    }
  },
  methods: {
    init(id) {
      console.log(id)
      this.dataForm = {}
      this.visible = true
      this.$refs['dataForm'].resetFields()
      if (id != 0) {
        console.log("获取数据")
        research.getBysubjectPkId(id).then((response) => {
          if (response.code == '000000') {
            console.log(response.data.vpInfo)
            let jsonObject = JSON.parse(response.data.vpInfo);
            console.log(jsonObject)
            let namesArray = jsonObject.map(item => item.name)
            this.dataForm = response.data
            this.dataForm.vpInfo = namesArray
          } else {
            this.$message.error('获取数据失败')
          }
        })
      }
      this.dataForm.id = id || 0 // 这一句其实可有可无的
      this.dataForm.vpInfo=["基线"]
      // this.dataForm.createPin = this.$store.getters.name
    },

    dataFormSubmit() {
      console.log(this.dataForm)
      if(this.dataForm.type === 0 && this.dataForm.id !== 0){
        this.$message.error("同步数据无法编辑");
        return;
      }
      console.log("提交")
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if (this.dataForm.id == 0) {
            const timestamp = Date.now();
            const randomDigits = Math.floor(Math.random() * 900) + 100; //时间戳+随机数当pk_id
            const resultString = timestamp + randomDigits;
            this.dataForm.subjectPkId = resultString;
            let flag = 0
            let vpString = this.dataForm.vpInfo.map((item, index) => {
              let codeNum
              if( item === "基线" && index === 0){
                codeNum = 0;
                flag = 1;
              }
              if(flag === 0){
                codeNum = "V" + (index + 1).toString();
              }else{
                codeNum = "V" + index.toString();
              } //访视阶段里code的生成规则
               return{
                 name: item,
                 order: index + 1,
                 code: codeNum
               }
            })
            this.dataForm.vpInfo2 = JSON.stringify(vpString)
            this.dataForm.type = 1
            console.log(this.dataForm)
            research.addResearch(this.dataForm).then(({ code }) => {
              if (code === '000000') {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 700,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          } else {
            let flag = 0
            let vpString = this.dataForm.vpInfo.map((item, index) => {
              let codeNum
              if( item === "基线" && index === 0){
                codeNum = 0;
                flag = 1;
              }
              if(flag === 0){
                codeNum = "V" + (index + 1).toString();
              }else{
                codeNum = "V" + index.toString();
              }
              return{
                name: item,
                order: index + 1,
                code: codeNum
              }
            })
            this.dataForm.vpInfo2 = JSON.stringify(vpString)
            this.dataForm.type = 1
            console.log(this.dataForm)
            research.updateResearch(this.dataForm).then(({ code }) => {
              if (code === '000000') {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 700,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        }
      })
    },

    handleClose(tag) {
      console.log("删")
      console.log(tag)
      this.dataForm.vpInfo.splice(this.dataForm.vpInfo.indexOf(tag), 1);
      console.log(this.dataForm)
      this.$forceUpdate()
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      console.log("确认了")
      console.log(this.inputValue)
      if(this.dataForm.vpInfo == null) {this.dataForm.vpInfo = ["基线"]}
      let inputValue = this.inputValue;
      let i = 0
      if (inputValue) {
      this.dataForm.vpInfo.forEach(vp => {
        if (inputValue === vp){
          this.$message.error("请勿输入重复信息");
          i = 1
        }
      })
      if(i === 0) this.dataForm.vpInfo.push(inputValue);
      }
      console.log(this.dataForm)
      this.inputVisible = false;
      this.inputValue = '';
    }
}
}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
